package com.example.oop.Service;

import com.example.oop.ChatRoom.ChatRoomManager;
import com.example.oop.POJO.ChessPlay;
import com.example.oop.POJO.Player;
import com.example.oop.Repository.ChessPlayRepository;
import com.example.oop.Repository.PlayerRepository;
import com.example.oop.Repository.RepositoryManager;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class PlayService {
    private final ChessPlayRepository chessPlayRepository;
    private final PlayerRepository playerRepository;

    public PlayService() {
        chessPlayRepository = RepositoryManager.chessPlayRepository;
        playerRepository = RepositoryManager.playerRepository;
    }

    //    该方法用来更改用户状态+创建对局（chess_play）
    //要求互斥进行
    public synchronized void beginPlay(Player player1, Player player2) {
        synchronized (RepositoryManager.chessPlayRepository) {
            synchronized (RepositoryManager.playerRepository) {
                //设置玩家状态并保存
                player1.setStatus(2);
                player1.setColor(1);

                player2.setStatus(2);
                player2.setColor(2);

                playerRepository.save(player1);
                playerRepository.save(player2);

                List<ChessPlay> all = chessPlayRepository.findAll();
                ChessPlay chessPlay = new ChessPlay(findMaxId(all) + 1, 1, player1.getUsername());
                chessPlay.setPlayer1Name(player1.getUsername());
                chessPlay.setPlayer2Name(player2.getUsername());
                chessPlayRepository.save(chessPlay);
            }
        }
    }

    //用户调用该方法获取当前对局信息（turn/color/对局状态/chessResult）
    public synchronized JSONObject getPlayStatus(JSONObject args) throws JSONException {
        synchronized (RepositoryManager.chessPlayRepository) {
            synchronized (RepositoryManager.playerRepository) {
                JSONObject jsonResp = new JSONObject();
                String username = args.optString("username");
//                System.out.println(username + "请求获取游戏状态");
                Integer playId = Integer.parseInt(args.optString("playId"));

                Player player = playerRepository.findByUsername(username).get(); //获取当前用户对应的玩家

                ChessPlay chessPlay = null;
                if (playId == 0) {  //（第一次获取对局信息时）根据用户名和对局状态进行查找
                    if (chessPlayRepository.findByPlayer1NameAndStatus(player.getUsername(), 1).isPresent()) {
                        chessPlay = chessPlayRepository.findByPlayer1NameAndStatus(player.getUsername(), 1).get(); //获取当前玩家的对局
                    } else if (chessPlayRepository.findByPlayer2NameAndStatus(player.getUsername(), 1).isPresent()) {
                        chessPlay = chessPlayRepository.findByPlayer2NameAndStatus(player.getUsername(), 1).get(); //获取当前玩家的对局
                    }
//                        System.out.println("findByUserName");
                } else {  //用户传入playId,根据对局id直接获取对局
                    chessPlay = chessPlayRepository.findById(playId).get();
//                        System.out.println("findById");
                }

                jsonResp.put("status", -1);

                if (chessPlay != null) {
                    JSONObject data = new JSONObject();
                    data.put("playId", chessPlay.getId());
                    data.put("status", chessPlay.getStatus());
                    data.put("chessResult", chessPlay.getChessResult());
                    data.put("color", player.getColor());
                    data.put("turn", chessPlay.getTurn());
                    data.put("player1", chessPlay.getPlayer1Name());
                    data.put("player2", chessPlay.getPlayer2Name());
                    //获取获胜者
                    String winner = "";
                    if (chessPlay.getWinner() != null) {
                        winner = chessPlay.getWinner();
                    }

//                    System.out.println(chessPlay);
                    data.put("winner", winner);

                    jsonResp.put("data", data);
                    jsonResp.put("status", 0);
                }

                return jsonResp;
            }
        }
    }

    //用户下子，对应到数据库
    public synchronized JSONObject doPlay(JSONObject args) {
        synchronized (RepositoryManager.chessPlayRepository) {
            JSONObject jsonResp = new JSONObject();

            String username = args.optString("username", "");
            Integer playId = Integer.parseInt(args.optString("playId", ""));

            jsonResp.put("status", -1);

//            System.out.println(args);
            if (chessPlayRepository.findById(playId).isPresent()) {
                ChessPlay chessPlay = chessPlayRepository.findById(playId).get();

//                System.out.println(chessPlay);

                //获取当前对局
//                System.out.println("用户"+username+"下棋");
                //  System.out.println(args.optString("chessResult", ""));
                chessPlay.setChessResult(args.optString("chessResult", ""));
                chessPlay.setTurn(args.optString("turn", ""));
                chessPlayRepository.save(chessPlay);

                jsonResp.put("status", 0);
                jsonResp.put("reason", "");
            }

            return jsonResp;
        }
    }

    //用户认输
    public synchronized JSONObject doConcede(JSONObject args) {
        synchronized (RepositoryManager.playerRepository) {
            synchronized (RepositoryManager.chessPlayRepository) {
                JSONObject jsonResp = new JSONObject();

                //根据用户名找到当前player
                String username = args.optString("username", "");
                String chatRoomId = args.optString("chatRoomId", "");  //获取chatRoom序号
                Player player = playerRepository.findByUsername(username).get();

                //修改当前player的状态为0，color为0
                player.setStatus(0);
                player.setColor(0);
                playerRepository.save(player);

                //根据player和状态找到当前进行的对局
                ChessPlay chessPlay = null;
                String winner = null;  //记录获胜者
                if (chessPlayRepository.findByPlayer1NameAndStatus(player.getUsername(), 1).isPresent()) {
                    //获取当前玩家（玩家1）的对局
                    chessPlay = chessPlayRepository.findByPlayer1NameAndStatus(player.getUsername(), 1).get();
                    winner = chessPlay.getPlayer2Name();  //玩家2为获胜者
                } else if (chessPlayRepository.findByPlayer2NameAndStatus(player.getUsername(), 1).isPresent()) {
                    //获取当前玩家（玩家2）的对局
                    chessPlay = chessPlayRepository.findByPlayer2NameAndStatus(player.getUsername(), 1).get();
                    winner = chessPlay.getPlayer1Name();  //玩家1为获胜者
                }

                //找到参与对局的另一名玩家，修改其状态和color
                Player player2 = playerRepository.findByUsername(winner).get();
                player2.setStatus(0);
                player2.setColor(0);
                playerRepository.save(player2);

                //设置对局胜利者为对方，状态为2
                chessPlay.setStatus(2);
                chessPlay.setWinner(winner);
                chessPlayRepository.save(chessPlay);

                //删除用户会话（包含其消息）
                if (chatRoomId != null && !chatRoomId.equals("")) {
                    ChatRoomManager.i.deleteChatRoom(Integer.parseInt(chatRoomId));
                }

                jsonResp.put("status", 0);
                jsonResp.put("reason", "您已认输。您可以选择重新开始游戏！");

                return jsonResp;
            }
        }
    }

    //有用户获胜
    public synchronized JSONObject doWin(JSONObject args) {
        synchronized (RepositoryManager.playerRepository) {
            synchronized (RepositoryManager.chessPlayRepository) {
                JSONObject jsonResp = new JSONObject();

                //根据用户名找到当前player(获胜玩家)
                String username = args.optString("username", "");
                String chatRoomId = args.optString("chatRoomId", "");  //获取chatRoom序号
                Player player = playerRepository.findByUsername(username).get();

                //修改当前player的状态为0，color为0
                player.setStatus(0);
                player.setColor(0);
                playerRepository.save(player);

                //根据player和状态找到当前进行的对局
                ChessPlay chessPlay = null;
                String otherPlayer = null;  //记录获胜者
                if (chessPlayRepository.findByPlayer1NameAndStatus(player.getUsername(), 1).isPresent()) {
                    //获取当前玩家（玩家1）的对局
                    chessPlay = chessPlayRepository.findByPlayer1NameAndStatus(player.getUsername(), 1).get();
                    otherPlayer = chessPlay.getPlayer2Name();  //玩家2为获胜者
                } else if (chessPlayRepository.findByPlayer2NameAndStatus(player.getUsername(), 1).isPresent()) {
                    //获取当前玩家（玩家2）的对局
                    chessPlay = chessPlayRepository.findByPlayer2NameAndStatus(player.getUsername(), 1).get();
                    otherPlayer = chessPlay.getPlayer1Name();  //玩家1为获胜者
                }

                //找到参与对局的另一名玩家，修改其状态和color
                Player player2 = playerRepository.findByUsername(otherPlayer).get();
                player2.setStatus(0);
                player2.setColor(0);
                playerRepository.save(player2);

                //设置对局胜利者为自己，状态为2
                chessPlay.setStatus(2);
                chessPlay.setWinner(username);
                chessPlayRepository.save(chessPlay);

                //删除用户会话（包含其消息）
                if (chatRoomId != null && !chatRoomId.equals("")) {
                    ChatRoomManager.i.deleteChatRoom(Integer.parseInt(chatRoomId));
                }

                jsonResp.put("status", 0);
                jsonResp.put("reason", "");

                return jsonResp;
            }
        }
    }

    private synchronized int findMaxId(List<ChessPlay> all) {
        int max = 0;
        for (ChessPlay play : all) {
            if (max < play.getId()) max = play.getId();
        }
        return max;
    }
}
